<template>
  <div class="app-container calendar-list-container">
      <!-- 搜索框，对工单单号,工单单别进行搜索 -->
    <div class="filter-container">
        <el-radio v-model="radio" label="1" @change="radioChange">
            <el-input
            clearable
            v-model="listQuery.workOrderNo"
            style="width: 150px;margin-right:15px;margin-top:7px"
            class="filter-item"
            placeholder="请输入工单单号"
            :disabled="radio != '1'"
            ></el-input>
            <el-input
                clearable
                v-model="listQuery.orderType"
                style="width: 150px;margin-right:15px;margin-top:7px"
                class="filter-item"
                placeholder="请输入工单单别"
                :disabled="radio != '1'"
            ></el-input>
        </el-radio>

        <el-radio v-model="radio" label="2" @change="radioChange">
            <el-input
            clearable
            v-model="orderPlanNo"
            style="margin-right:15px;margin-top:7px"
            :style="{ width: inputWid(orderPlanNo) }"
            class="filter-item"
            placeholder="请输入计划批号"
            :disabled="radio != '2'"
            ></el-input>
        </el-radio>
      
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">查询</el-button>
      <!-- <el-button
            type="button"
            class="el-button el-button--warning filter-item"
            @click="loading = false"
          >
            取消</el-button> -->
      <el-button class="filter-item" :loading="btnLoading" type="primary" v-waves @click="dialogFormVisible = true">查询结果</el-button>
    </div>

    <div class="btn-button" v-if="orderList3.length">
        <el-button type="warning" @click="showModifyTime = true">批量修改</el-button>
        <el-button type="primary" @click="intercept('form')">确定提交</el-button>
        <!-- <el-button type="primary" @click="resetForm('form')">重置</el-button> -->
    </div>
    <!-- 工单信息列表 -->
    <el-collapse v-model="activeName" accordion>
     <el-collapse-item :title="'工单：' + item.orderType + '-' + item.workOrderNo" :name="index" v-for="(item,index) in orderList3" :key="index">
        <el-form ref="form" :model="item" label-width="120px" size="medium">
            <el-form-item label="工单单号" prop="workOrderNo" >
                <el-input v-model="item.workOrderNo" style="width:300px" disabled />
            </el-form-item>
            <el-form-item label="工单单别" prop="orderType">
                <el-input v-model="item.orderType" style="width:300px" disabled />
            </el-form-item>
            <!-- <el-form-item label="工段编号" prop="sectionNo" required>
                <el-select v-model="item.sectionNo" placeholder="请选择工段编号" @focus="getSection" style="width:300px">
                    <el-option :value="item" :label="item" v-for="(item,index) in sectionList" :key="index"/>
                </el-select>
            </el-form-item> -->
            <el-form-item label="排产时间" prop="planTime" required>
                <el-date-picker :clearable="false" v-model="item.planTime"  format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" placeholder="选择日期时间" style="width:300px" />
            </el-form-item>
            <el-form-item label="排产数量" prop="planNumber" required>
                <el-input v-model="item.planNumber" style="width:300px"/>
            </el-form-item>
            <el-form-item label="剩余可排产数量" prop="surplusAmount">
                <el-input v-model="item.surplusAmount" style="width:300px" disabled />
            </el-form-item>
            <el-form-item label="预计产量" prop="estimateYield">
                <el-input v-model="item.estimateYield" style="width:300px" disabled />
            </el-form-item>
            <el-form-item label="BOM时间" prop="bomTimeStr">
                <el-input v-model="item.bomTimeStr" style="width:300px" disabled />
            </el-form-item>
            <el-form-item label="BOM版本" prop="bomVersion">
                <el-input v-model="item.bomVersion" style="width:300px" disabled />
            </el-form-item>
            <el-form-item label="非标信息" prop="notStandard">
                <el-input v-model="item.notStandard" style="width:300px" disabled />
            </el-form-item>
            <el-form-item label="免检信息" prop="exemption">
                <el-input v-model="item.exemption" style="width:300px" disabled />
            </el-form-item>
            <el-form-item label="预计开始时间" prop="estimateStartTimeStr">
                <el-date-picker
                v-model="item.estimateStartTimeStr"
                format="yyyy-MM-dd" 
                value-format="yyyy-MM-dd" 
                type="date"
                placeholder="选择预计开始时间"
                style="width:300px"
                :clearable="false">
                </el-date-picker>
                <!-- <el-input v-model="item.estimateStartTimeStr" style="width:300px"  disabled/> -->
            </el-form-item>
            <el-form-item label="预计结束时间" prop="estimateEndTimeStr" required>
                <el-date-picker
                v-model="item.estimateEndTimeStr"
                format="yyyy-MM-dd" 
                value-format="yyyy-MM-dd" 
                type="date"
                placeholder="选择预计结束时间"
                style="width:300px"
                :clearable="false">
                </el-date-picker>
                <!-- <el-input v-model="item.estimateEndTimeStr" style="width:300px" disabled/> -->
            </el-form-item>
            <el-form-item label="工作中心" prop="workCenter">
                <el-input v-model="item.workCenter" style="width:300px" disabled />
            </el-form-item>
            <el-form-item label="产品名称" prop="produceName">
                <el-input v-model="item.produceName" style="width:300px" disabled />
            </el-form-item>
            <el-form-item label="产品规格" prop="specification">
                <el-input v-model="item.specification" style="width:300px" disabled />
            </el-form-item>
        </el-form>
     </el-collapse-item>
    </el-collapse>
    
    <!-- 选择工单 -->
    <el-dialog title="批量添加工单" :visible.sync="dialogFormVisible" width="700px">
         <div style="text-align: center" class="edit_dev">
            <el-transfer
            style="text-align: left; display: inline-block"
            v-model="orderList4"
            filterable
            :titles="['未选中', '选中']"
            :format="{
                noChecked: '${total}',
                hasChecked: '${checked}/${total}'
            }"
            @change="handleChange"
            :data="orderList2"
            target-order="unshift">
            <span slot-scope="{ option }">{{ option.label }}</span>
            </el-transfer>
        </div>
    </el-dialog>

    <!-- 上传失败弹窗 -->
    <el-dialog title="添加工单失败列表" :visible.sync="errorDialog" width="500px">
        <div v-for="(item,index) in errorLists" :key="index">
            <el-link :underline="false">{{item.planNo}}:</el-link>
            <el-link :underline="false" type="warning">{{item.errMsg}}</el-link>
        </div>
        <el-divider></el-divider>
        <div class="errorBtn">
            <el-button type="primary" @click="errorSure">确定</el-button>
        </div>
    </el-dialog>

    <!-- 批量修改弹出表单 -->
    <el-dialog title="批量修改" :visible.sync="showModifyTime" width="600px">
    <el-form :model="modifyform">
      <!-- <el-form-item label="工段编号" :label-width="formLabelWidth">
        <el-select v-model="modifyform.sectionNo" placeholder="请选择工段编号" @focus="getSection" style="width:400px;margin-right:15px;">
            <el-option :value="item" :label="item" v-for="(item,index) in sectionList" :key="index"/>
        </el-select>
      </el-form-item> -->
      <el-form-item label="排产时间" :label-width="formLabelWidth">
         <el-date-picker 
         v-model="modifyform.planTime"  
         format="yyyy-MM-dd HH:mm:ss" 
         value-format="yyyy-MM-dd HH:mm:ss" 
         type="datetime" 
         placeholder="选择排产时间" 
         style="width:400px" />
      </el-form-item>
      <el-form-item label="预计开始时间" :label-width="formLabelWidth">
         <el-date-picker
            v-model="modifyform.estimateStartTimeStr"
            format="yyyy-MM-dd" 
            value-format="yyyy-MM-dd" 
            type="date"
            placeholder="选择预计开始时间"
            style="width:400px"
            :clearable="false">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="预计结束时间" :label-width="formLabelWidth">
         <el-date-picker
            v-model="modifyform.estimateEndTimeStr"
            format="yyyy-MM-dd" 
            value-format="yyyy-MM-dd" 
            type="date"
            placeholder="选择预计结束时间"
            style="width:400px"
            :clearable="false">
        </el-date-picker>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="showModifyTime = false">取 消</el-button>
      <el-button type="primary" @click="modifyTime">确 定</el-button>
    </div>
    </el-dialog>
  </div>
</template>

<script>
import { orderInfo, addOrderPlan, getSectionList,getOrderByNoSK,saveOrderPt,getOrderByNoPT } from '../../api/productionPlan'
import { WorkSecExist } from '../../api/workSection.js'
export default {
    name: 'sprayAddplan',
    data() {
        return {
            activeName: '工单列表',
            orderPlanNo: '',                            //计划批号
            listQuery: {
                workOrderNo: '',						//工单单号
                orderType: ''							//工单单别
            },
            // 产品信息表单，需提交后台
            form: {
                workOrderNo: '',						//工单单号
                orderType: '',							//工单单别
                // sectionNo: '',							//工段编号
                planNumber: '',							//排产数量
                planTime: '',							//排产时间
                bomTimeStr: '',							//BOM时间
                bomVersion: '',							//BOM版本
                notStandard: '',						//非标信息
                estimateStartTimeStr: '',				//预计开始时间
                estimateEndTimeStr: '',					//预计结束时间
                estimateYield: '',						//预计产量
                workCenter: '',							//工作中心
                produceName: '',						//产品名称
                specification: '',						//产品规格
                surplusAmount: '',						//剩余可排产数量
                exemption: ''							//免检标志位
            },
            sectionList: null,							//已经录入后台的工段编号
            orderList2: [],     //穿梭框左侧列表
            dialogFormVisible: false,
            orderList4: [],     //穿梭框右侧列表
            orderList3: [],     //折叠列表.length == 穿梭框右侧列表.length
            orderList1: [],      //全部工单
            errorLists: [],       //排产失败列表
            errorDialog: false,
            radio: '2',
            times: 0,               //添加数据请求次数
            modifyform: {
                planTime: '',
                estimateStartTimeStr: '',
                estimateEndTimeStr: '',
                // sectionNo: ''
            },
            showModifyTime: false,
            formLabelWidth: '100px',                    //批量修改时间输入框的长度控制
            btnLoading: false
        }
    },
    computed: {
      inputWid() {
        return function (value) {
            if(!value || (value.length <= 10)){
              return '150px'
            } else {
              return (150 + (String(value).length-10)*6) + 'px'
            }
        }
      }
    },
    methods: {
        errorSure(){
            this.errorDialog = false
            this.errorLists = []
        },
        // 清空缓存
        radioChange(e){
            console.log(e)
            this.orderList1 = []
            this.orderList2 = []
            this.orderList3 = []
            this.orderList4 = []
            this.errorLists = []
            this.listQuery = {
                workOrderNo: '',
                orderType: ''
            }
            this.orderPlanNo = ''
        },
        // 输入工单单号与工单单别，查询相应的数据
        async handleFilter() {
            if (this.radio == '2' && this.orderPlanNo == '') return this.$message({
                message: '计划批号不能为空',
                type: 'warning'
            })
            if (this.radio == '1') {
                if(this.listQuery.orderType == '' || this.listQuery.workOrderNo == '') return this.$message({
                message: '工单单别或者工单单号不能为空',
                type: 'warning'
                })
            }
            this.btnLoading = true
            let query = {}
            if(this.radio == '1') {
                query.orderType = this.listQuery.orderType
                query.workOrderNo = this.listQuery.workOrderNo
            } else {
                query.orderPlanNo = this.orderPlanNo
            }
            query.isSpray = true
            let data = await getOrderByNoPT(query)
            this.btnLoading = false
            if(data.code == '2') return this.$message.error(data.msg)
            this.orderList1 = data.data
            this.orderList1.forEach(item33 => {
                item33.estimateStartTimeStr = this.timeformat2(item33.estimateStartTimeStr)
                item33.estimateEndTimeStr = this.timeformat2(item33.estimateEndTimeStr)
            });
            this.dialogFormVisible = true
            let arr = JSON.parse(JSON.stringify(data.data))
            this.orderList2 = []
            this.orderList3 = []
            arr.forEach((item,index) => {
                let obj = {}
                obj.key = index
                obj.label = item.orderType + '-' + item.workOrderNo
                this.orderList2.push(obj)
            });
            this.orderList4 = []
            // 重置批量修改时间
            this.modifyform = {
                planTime: '',
                estimateStartTimeStr: '',
                estimateEndTimeStr: '',
                // sectionNo: ''
            }
        },
        // 拦截，提示是否确定提交
        intercept(value){
            if(!this.orderList3.length) return this.$message({
                message: '请先选择工单',
                type: 'warning'
             })
            this.$confirm('确定工单信息是否无误', '注意', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.divideDatas()
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        // 每条数据请求一次
        divideDatas(){
            this.errorLists = []
            this.orderList3.forEach((item,index) => {
                this.onSubmit(item,index)
            });
        },
        // 将工单信息表单提交到后台
        async onSubmit(item,index) {
            let query = Object.assign({},item)
            delete query.sectionNo
            query.notStandard = (query.notStandard == '标准') ? 'N' : 'Y'
            query.exemption = (query.exemption == '免检') ? '0' : '1'
            query.estimateStartTimeStr = query.estimateStartTimeStr.split('-')[0] + query.estimateStartTimeStr.split('-')[1] + query.estimateStartTimeStr.split('-')[2]
            query.estimateEndTimeStr = query.estimateEndTimeStr.split('-')[0] + query.estimateEndTimeStr.split('-')[1] + query.estimateEndTimeStr.split('-')[2]
            query.isSpray = true
           const data = await saveOrderPt(query)
            this.times++
            const errMsg = data.msg
            if(data.code == '1'){
                this.orderList3.forEach((item3,index3) => {
                    if(item3.orderType == item.orderType && item3.workOrderNo == item.workOrderNo) {
                        this.orderList3.splice(index3,1)
                        this.orderList4.splice(index3,1)
                    }
                });
                this.orderList1.forEach((item1,index1) => {
                    if(item1.orderType == item.orderType && item1.workOrderNo == item.workOrderNo) {
                        this.orderList1[index1].surplusAmount = 0
                    }
                });
         	} else {
                let obj = {
                    planNo: item.orderType + '-' + item.workOrderNo,
                    errMsg
                }
              	this.errorLists.push(obj)
            }
            if(this.orderList3.length){
                if(this.errorLists.length){
                    this.errorDialog = true
                }
            } else {
                // 重置批量修改时间
                this.modifyform = {
                    planTime: '',
                    estimateEndTimeStr: '',
                    estimateStartTimeStr: '',
                    // sectionNo: ''
                }
                this.$message({
                    message: '添加成功',
                    type: 'success'
                 })
            }
        },
        // 穿梭框选中列表
        handleChange(value, direction, movedKeys) {
            console.log(value, direction, movedKeys);
            let arr = []
            value.forEach(items => {
                this.orderList1.forEach((item,index) => {
                    if(items == index){
                        // item.sectionNo = '010101'
                        item.planNumber = item.surplusAmount
                        item.planTime = this.modifyform.planTime?this.modifyform.planTime:this.timeformat(item.estimateStartTimeStr)
                        item.estimateStartTimeStr = this.modifyform.estimateStartTimeStr?this.modifyform.estimateStartTimeStr:item.estimateStartTimeStr
                        item.estimateEndTimeStr = this.modifyform.estimateEndTimeStr?this.modifyform.estimateEndTimeStr:item.estimateEndTimeStr
                        arr.push(item)
                    }
                })
            });
            arr.forEach(item1 => {
                item1.notStandard = (item1.notStandard == 'N') ? '标准' : '非标'
                item1.exemption = (item1.exemption == '0')  ? '免检' : '非免检'
            });
            this.orderList3 = arr
            console.log(this.orderList3)
        },
        timeformat(val){
            return val + ' ' + '00:00:00'
        },
        timeformat2(val){
            return val.substring(0,4) + '-' + val.substring(4,6) + '-' + val.substring(6,8)
        },
        modifyTime(){
            if(this.modifyform.planTime == '' && this.modifyform.estimateEndTimeStr == '' && this.modifyform.estimateStartTimeStr == '' && !this.modifyform.sectionNo){
                this.showModifyTime = false
                return
            }
            this.orderList3.forEach(item => {
                // if(this.modifyform.sectionNo) {item.sectionNo = this.modifyform.sectionNo}
                if(this.modifyform.planTime){item.planTime = this.modifyform.planTime}
                if(this.modifyform.estimateStartTimeStr){item.estimateStartTimeStr = this.modifyform.estimateStartTimeStr}
                if(this.modifyform.estimateEndTimeStr){item.estimateEndTimeStr = this.modifyform.estimateEndTimeStr}
            });
            this.$message.success('操作完成!')
            this.showModifyTime = false
        },
        // 工段编号sectionNo下拉触发函数
        async getSection() {
            const data = await getSectionList()
            this.sectionList = data.data
        },
        // 对整个表单输入进去清空
        resetForm(formItem) {
          this.$refs[formItem].resetFields()
        },
    }
}
</script>

<style scoped>
.btn-button{
    display: flex;
    justify-content: flex-end;
    margin-bottom: 20px;
}
 .transfer-footer {
    margin-left: 20px;
    padding: 6px 5px;
  }
   .edit_dev >>> .el-transfer-panel {
     width:220px;
   }
   .errorBtn{
    display: flex;
    justify-content: flex-end;
   }
</style>